#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define GPIO_NUMBER "132"
#define GPIO_PATH "/sys/class/gpio/gpio" GPIO_NUMBER "/"
#define GPIO_EXPORT_PATH "/sys/class/gpio/export"
#define GPIO_UNEXPORT_PATH "/sys/class/gpio/unexport"
#define GPIO_DIRECTION_PATH GPIO_PATH "direction"
#define GPIO_VALUE_PATH GPIO_PATH "value"

void write_to_file(const char *path, const char *value) {
    int fd = open(path, O_WRONLY);
    if (fd < 0) {
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }
    if (write(fd, value, strlen(value)) < 0) {
        perror("Error writing to file");
        close(fd);
        exit(EXIT_FAILURE);
    }
    close(fd);
}

void blink_led(int blink_count, int delay_ms) {
    int fd = open(GPIO_VALUE_PATH, O_WRONLY);
    if (fd < 0) {
        perror("Error opening GPIO value file");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < blink_count; i++) {
        // 设置高电平 (LED ON)
        if (write(fd, "1", 1) != 1) {
            perror("Error writing GPIO value (ON)");
            close(fd);
            exit(EXIT_FAILURE);
        }
        usleep(delay_ms * 1000); // 延迟 delay_ms 毫秒

        // 设置低电平 (LED OFF)
        if (write(fd, "0", 1) != 1) {
            perror("Error writing GPIO value (OFF)");
            close(fd);
            exit(EXIT_FAILURE);
        }
        usleep(delay_ms * 1000); // 延迟 delay_ms 毫秒
    }

    close(fd);
}

int main() {
    // 1. 导出GPIO
    write_to_file(GPIO_EXPORT_PATH, GPIO_NUMBER);

    // 2. 等待系统生成GPIO文件
    usleep(100000); // 等待100毫秒（0.1秒）

    // 3. 设置GPIO方向为输出
    write_to_file(GPIO_DIRECTION_PATH, "out");

    // 4. 缓慢闪烁LED (闪烁10次，每次间隔500毫秒)
    printf("LED is blinking...\n");
    blink_led(10, 500); // 闪烁10次，每次500毫秒

    // 5. 取消导出GPIO
    write_to_file(GPIO_UNEXPORT_PATH, GPIO_NUMBER);

    printf("Blinking finished.\n");
    return 0;
}
